<template>
  <view class="quick-login-btn-area">
    <!-- 权限说明 -->
    <view class="permission-guide">
      <text class="guide-text">为了保障账户安全，需要获取您的手机号进行验证</text>
    </view>

    <!-- #ifdef MP-WEIXIN -->
    <button
      open-type="getPhoneNumber"
      @getphonenumber="handleWechatPhoneLogin"
      class="quick-login-btn weixin-login"
      :disabled="props.loading"
    >
      {{ props.loading ? '登录中...' : '当前手机号快捷登录' }}
    </button>
    <!-- #endif -->

    <!-- #ifndef MP-WEIXIN -->
    <wd-button
      custom-class="quick-login-btn"
      @click="handleWechatPhoneLogin"
      :loading="props.loading"
    >
      当前手机号快捷登录
    </wd-button>
    <!-- #endif -->

    <view class="switch-login-way">
      <text class="switch-login-way-text" @click="$emit('switch-way', 2)">短信登录</text>
      <text class="switch-login-way-text" @click="$emit('switch-way', 1)" style="margin-left: 20px">
        用户注册
      </text>
    </view>
  </view>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'wot-design-uni'
import { http } from '@/utils/http'
import { userApi } from '@/api/api'
import { useUserStore } from '@/store/user'

interface Props {
  loading?: boolean
}

interface Emits {
  (e: 'update:loading', value: boolean): void
  (e: 'switch-way', value: number): void
  (e: 'login-success'): void
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
})

const emit = defineEmits<Emits>()

const toast = useToast()
const userStore = useUserStore()

// 微信手机号快捷登录
const handleWechatPhoneLogin = async (e: any) => {
  emit('update:loading', true)

  try {
    // #ifdef MP-WEIXIN
    if (e.detail && e.detail.errMsg !== 'getPhoneNumber:ok') {
      // 用户拒绝授权处理
      toast.warning('需要手机号授权才能登录')
      // 引导用户手动授权或切换其他登录方式
      uni.showModal({
        title: '温馨提示',
        content: '需要获取您的手机号才能完成登录，是否切换到其他登录方式？',
        confirmText: '切换登录',
        cancelText: '重新授权',
        success: function (res) {
          if (res.confirm) {
            emit('switch-way', 2) // 切换到短信登录
          }
        },
      })
      return
    }

    const [loginRes, phoneRes] = await Promise.all([
      new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: resolve,
          fail: reject,
        })
      }),
      Promise.resolve(e.detail ? e.detail.code : null),
    ])

    const params = {
      code: phoneRes,
    }

    const res = await http.post(userApi.getUserPhoneByWx, params)

    if (res.success) {
      // 缓存授权成功状态
      uni.setStorageSync('wechatPhoneAuthStatus', 'authorized')
      await performLogin(res.result.phone)
    } else {
      throw new Error(res.message || '获取手机号失败')
    }
    // #endif

    // #ifndef MP-WEIXIN
    // 非微信环境模拟数据
    console.log('现在使用的是非微信登陆')
    await performLogin('15975368421') // 模拟管理员手机号
    // #endif
  } catch (err: any) {
    toast.warning(err.message || '登录失败')
    // 记录错误日志
    console.error('登录失败:', err)
  } finally {
    emit('update:loading', false)
  }
}

// 执行登录操作
const performLogin = async (phoneNumber: string, captcha: string = null) => {
  const loginParams = {
    username: phoneNumber,
    ...(captcha && { captcha }),
  }

  try {
    const res = await http.post(userApi.miniLogin, loginParams)
    if (res.success) {
      const { result } = res
      const userInfo = result.userInfo

      userStore.setUserInfo({
        token: result.token,
        userid: userInfo.id,
        username: userInfo.username,
        realname: userInfo.realname,
        avatar: userInfo.avatar,
        phone: userInfo.phone,
        tenantId: userInfo.loginTenantId,
        localStorageTime: +new Date(),
        userRoleName: userInfo.userRoleName,
        userRole: userInfo.userRole,
        checkStatus: userInfo.checkStatus,
        // 初始化权限列表
        permissionList: [],
      })

      // 获取用户权限列表
      try {
        const permissionList = await http.get(userApi.getUserPermissionsBytoken)
        userStore.setPermissionList(permissionList?.result?.codeList || [])
      } catch (permissionError) {
        console.warn('获取权限列表失败:', permissionError)
      }

      // 检查账户状态
      if (userInfo.checkStatus === 0) {
        toast.warning('当前用户未解封，请联系管理员')
      }

      emit('login-success')
    } else {
      toast.warning(res.message)
    }
  } catch (err: any) {
    const msg = err.message || '请求出现错误，请稍后再试'
    toast.warning(msg)
  }
}
</script>

<style lang="scss" scoped>
.quick-login-btn-area {
  padding-top: 100px;
  width: 87%;
  margin: 0 auto;
}

.permission-guide {
  background-color: #f0f8ff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 20px;
  text-align: center;

  .guide-text {
    color: #666;
    font-size: 14px;
    line-height: 1.4;
  }
}

.quick-login-btn {
  width: 100%;
  --wot-button-medium-height: 45px;
  --wot-button-medium-fs: 16px;
}

.switch-login-way {
  text-align: center;
  margin-top: 20px;

  .switch-login-way-text {
    color: #007aff;
    font-size: 14px;
  }
}

.weixin-login {
  background-color: #007aff;
  border-radius: 25upx;
  color: white;
  font-weight: bold;

  &:disabled {
    background-color: #cccccc;
  }
}
</style>
